import MysqlCore from "../core/MysqlCore";
import TableInfo from "./TableInfo";

class DatabaseInfo {
    public name: string;
    protected tableMap: Map<string, TableInfo> = new Map();

    constructor(name: string) {
        this.name = name;
    }

    public add(tabel: TableInfo) {
        this.tableMap.set(tabel.name, tabel)
    }

    public has(name: string) {
        return this.tableMap.has(name)
    }

    public get(name: string) {
        return this.tableMap.get(name)
    }


    public static async getAll_Table(DB: MysqlCore): Promise<DatabaseInfo> {
        let database = DB.mysqlConfig.database;
        // 获取到所有的表名 [ TextRow { Tables_in_cs: 'user' } ]
        let tableList = (await DB.nativeSelect<Array<any>>("show tables")).map(e => e.Tables_in_nestling);
        let table: DatabaseInfo = new DatabaseInfo(database);
        // 遍历表名
        for (let tableName of tableList) {
            //key是表名，查询表中的key值
            // 获取表中的key键
            let sql = `SELECT k.column_name, k.table_name
                       FROM information_schema.table_constraints t
                                JOIN information_schema.key_column_usage k
                                     USING (constraint_name, table_schema, table_name)
                       WHERE table_schema = '${database}'
                         AND t.constraint_type = 'PRIMARY KEY'
                         AND k.table_name = '${tableName}'`.replace(/\n| +/g, " ");

            let tab = await DB.nativeSelect<Array<any>>(sql);

            if (tab.length >= 1) {
                //获取表中的所有字段
                let sql = `select COLUMN_NAME
                           from information_schema.COLUMNS
                           where table_schema = '${database}'
                             and table_name = '${tableName}'`.replace(/\n| +/g, " ");
                let field = await DB.nativeSelect(sql) as Array<any>;
                field = field.map((res) => res.COLUMN_NAME);
                table.add(new TableInfo(tab[0].table_name, tab[0].column_name, field))
            }
        }
        return table;
    }
}

export = DatabaseInfo;